package com.example.lirisheng.springbootfinalexperiment.security.provider;

import com.alibaba.fastjson.JSONObject;
import com.example.lirisheng.springbootfinalexperiment.entity.Users;
import com.example.lirisheng.springbootfinalexperiment.repositories.UserRoleRepository;
import com.example.lirisheng.springbootfinalexperiment.repositories.UsersRepository;
import com.example.lirisheng.springbootfinalexperiment.util.JSON;
import com.example.lirisheng.springbootfinalexperiment.util.Jcode2SessionUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.security.authentication.AuthenticationProvider;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Component;

import java.util.HashSet;
import java.util.Map;
import java.util.Set;

@Component
public class WeiAuthenticationProvider implements AuthenticationProvider {

    @Value("${weChat.appid}")
    private  String appid;
    @Value("${weChat.secret}")
    private String secret;
    @Autowired
    UsersRepository usersRepository;
    @Autowired
    UserRoleRepository userRoleRepository;

    @Override
    public Authentication authenticate(Authentication authentication) throws AuthenticationException {
        String code =(String) authentication.getPrincipal();

        Map<String,Object> infoMap;
        try{
            String sessionInfo1 = Jcode2SessionUtil.jscode2session(appid,secret,code,"authorization_code");//登录grantType固定
            infoMap = JSON.readValue(sessionInfo1);
        }catch (Exception exception){
            System.out.println("message:"+exception.getMessage());
            throw  new UsernameNotFoundException("微信登录失败");
        }

        //1.判断是否有绑定账号
        String openId=(String)infoMap.get("openid");
        //根据openid来判断是否绑定,是否被锁定
        Users users = usersRepository.findByOpenId(openId);
        if(users==null){
            //账号不存在
            throw  new UsernameNotFoundException("账号不存在");
        }
        if(users.getEnabled()==0){
            //账号不存在
            throw  new UsernameNotFoundException("账号被锁");
        }

        Set<SimpleGrantedAuthority> grantRoles = new HashSet<>();
        Set<String> roles = userRoleRepository.findRoleByUserId(users.getId());
        roles.stream().forEach(out->grantRoles.add(new SimpleGrantedAuthority(out)));

        //查出权限 ,构造一个authentication,返回给前端
        UsernamePasswordAuthenticationToken authRequest = new UsernamePasswordAuthenticationToken(openId, null,grantRoles);
        return  authRequest;
    }

    @Override
    public boolean supports(Class<?> aClass) {
        return aClass.equals(UsernamePasswordAuthenticationToken.class);
    }
}
